package com.hnayan.websocketexample.web;

import com.hnayan.websocketexample.dto.Reply;
import com.hnayan.websocketexample.dto.Message;
import com.hnayan.websocketexample.dto.User;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * Created by hnayan on 2017/8/4.
 */
@Controller
public class ChatRoomController {
    //常量
    private static final String SEND_TO = "/topic/reply";
    private static final String MESSAGE_MAPPING = "/hello";

    @MessageMapping(MESSAGE_MAPPING)
    @SendTo(SEND_TO)
    public Reply reply(Message message) throws InterruptedException {
        return new Reply(message);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        if(!"".equals(userName) && !Objects.equals(password, "")){
            User user =new User(userName,password);
            request.getSession().setAttribute("user",user);
            redirectAttributes.addFlashAttribute("user", user);
            return "redirect:/index";
        }else{
            model.addAttribute("error", "Login no pass.");
            return "/login";
        }
    }
    @RequestMapping("/login")
    public String login() {
        return "/login";
    }
    @RequestMapping({"/","/index"})
    public String index() {
        return "/index";
    }

    @RequestMapping("/logout")
    @ResponseBody
    public String logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "success";
    }

}
